
// 生成唯一ID的函数
function generateUUID(): string {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0,
      v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

// 格式化时间
function formatTime(timestamp: number): string {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  
  return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`;
}

Page({
  data: {
    postId: '',
    post: null,
    comments: [],
    commentContent: '',
    userId: '',
    isAuthor: false
  },

  onLoad(options: any) {
    const postId = options.id;
    this.setData({
      postId,
      userId: wx.getStorageSync('userId') || ''
    });
    
    this.loadPostDetail();
  },

  loadPostDetail() {
    const { postId, userId } = this.data;
    
    // 获取帖子列表
    const posts = wx.getStorageSync('posts') || [];
    
    // 查找当前帖子
    const post = posts.find((p: any) => p.id === postId);
    
    if (post) {
      // 格式化时间
      post.formattedTime = formatTime(post.createTime);
      
      // 检查当前用户是否是作者
      const isAuthor = post.author === userId;
      
      // 获取评论列表
      let comments = post.comments || [];
      
      // 格式化评论时间
      comments = comments.map((comment: any) => {
        return {
          ...comment,
          formattedTime: formatTime(comment.createTime)
        };
      });
      
      this.setData({
        post,
        comments,
        isAuthor
      });
    } else {
      wx.showToast({
        title: '帖子不存在',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    }
  },

  onCommentInput(e: any) {
    this.setData({
      commentContent: e.detail.value
    });
  },

  submitComment() {
    const { commentContent, postId, userId } = this.data;
    
    // 验证输入
    if (!commentContent.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }
    
    // 创建新评论
    const newComment = {
      id: generateUUID(),
      postId,
      content: commentContent,
      author: userId,
      authorName: '匿名用户',
      createTime: new Date().getTime()
    };
    
    // 获取帖子列表
    let posts = wx.getStorageSync('posts') || [];
    
    // 查找当前帖子索引
    const postIndex = posts.findIndex((p: any) => p.id === postId);
    
    if (postIndex !== -1) {
      // 添加评论到帖子
      if (!posts[postIndex].comments) {
        posts[postIndex].comments = [];
      }
      
      posts[postIndex].comments.push(newComment);
      
      // 保存到本地存储
      wx.setStorageSync('posts', posts);
      
      // 清空输入并刷新评论列表
      this.setData({
        commentContent: ''
      });
      
      // 重新加载帖子详情
      this.loadPostDetail();
      
      wx.showToast({
        title: '评论成功',
        icon: 'success'
      });
    }
  },

  deleteComment(e: any) {
    const commentId = e.currentTarget.dataset.id;
    const { postId } = this.data;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      success: (res) => {
        if (res.confirm) {
          // 获取帖子列表
          let posts = wx.getStorageSync('posts') || [];
          
          // 查找当前帖子索引
          const postIndex = posts.findIndex((p: any) => p.id === postId);
          
          if (postIndex !== -1) {
            // 过滤掉要删除的评论
            posts[postIndex].comments = posts[postIndex].comments.filter(
              (c: any) => c.id !== commentId
            );
            
            // 保存到本地存储
            wx.setStorageSync('posts', posts);
            
            // 重新加载帖子详情
            this.loadPostDetail();
            
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
          }
        }
      }
    });
  },

  deletePost() {
    const { postId } = this.data;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这篇帖子吗？',
      success: (res) => {
        if (res.confirm) {
          // 获取帖子列表
          let posts = wx.getStorageSync('posts') || [];
          
          // 过滤掉要删除的帖子
          posts = posts.filter((p: any) => p.id !== postId);
          
          // 保存到本地存储
          wx.setStorageSync('posts', posts);
          
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            success: () => {
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/index/index'
                });
              }, 1500);
            }
          });
        }
      }
    });
  }
});